<?php
require 'model-db-connection/config.php';
$config = require 'model-db-connection/qrc_conf.properties.php';
$searchCondition = $_GET['searchCondition'];
$teamName = $_GET['teamName'];
$teamCode = $_GET['teamCode'];
$teamLead = $_GET['teamLead'];
$teamSkill = $_GET['teamSkill'];
$teamType = $_GET['teamType'];
$teamManager = $_GET['teamManager'];
?>
<div class="widget">
    <div class="widget-head">
        <h4 class="heading">Team Building (ทีมสร้าง)</h4>
        <a href="#modal-team" data-toggle="modal" class="btn btn-xs btn-inverse pull-right" id="new_team_btn" style="margin-top: 6px;"><i class="fa fa-plus fa-fw"></i> New Team Beuilder</a>
        <div class="clearfix"></div>
    </div>
    <div class="widget-body innerAll inner-2x">
        <!-- Table -->
        <table class="footable table table-striped table-primary dynamicTable tableTools" id="dataTables-team">

            <!-- Table heading -->
            <thead>
                <tr>
                    <th data-class="expand" class="center">Team Code</th>
                    <th class = "center">Team Name</th>
                    <th class = "center">Team Leader</th>
                    <th class = "center">Team Type</th>
                    <th class = "center">No. of member</th>
                    <th class = "center">Remark</th>
                    <th></th>
                </tr>
            </thead>
            <!-- // Table heading END -->
            <!-- Table body -->
            <tbody>
                <?php
                if ($searchCondition == "search_all") {
                    $sqlSelectTeamAll = "SELECT qtb.tCode AS t_code,"
                            . "qtb.tName AS t_Name,"
                            . "qtb.tLead_memid AS t_lead_id,"
                            . "qtb.tType AS t_type,"
                            . "qmr.memName AS t_lead_name,"
                            . "qtb.tRemark AS t_remark"
                            . " FROM QRC_TEAM_BUILDER qtb"
                            . " LEFT JOIN QRC_MEMBERS qmr ON qtb.tLead_memid = qmr.memID"
                            . " ORDER BY qtb.tCode DESC;";
                } else {
                    $checkTeamCode = !empty($teamCode) ? " AND qtb.tCode LIKE '%$teamCode%'" : "";
                    $checkTeamName = !empty($teamName) ? " AND qtb.tName LIKE '%$teamName%'" : "";
                    $checkTeamLead = !empty($teamLead) ? " AND qtb.tLead_memid LIKE '$teamLead'" : "";
                    $checkTeamType = !empty($teamType) ? " AND qtb.tType LIKE '$teamType'" : "";
                    $checkTeamManager = !empty($teamManager) ? " AND qtb.tManager_memid LIKE '$teamManager'" : "";
                    if ($teamSkill == "null") {
                        $checkTeamSkill = "";
                    } else {
                        $checkTeamSkill = !empty($teamSkill) ? " AND qtb.tSkill IN ($teamSkill)" : "";
                    }
                    $sqlSelectTeamAll = "SELECT qtb.tCode AS t_code,"
                            . "qtb.tName AS t_Name,"
                            . "qtb.tLead_memid AS t_lead_id,"
                            . "qtb.tType AS t_type,"
                            . "qmr.memName AS t_lead_name,"
                            . "qtb.tRemark AS t_remark"
                            . " FROM QRC_TRAM_BUILDER qtb"
                            . " LEFT JOIN QRC_MEMBERS qmr ON qtb.tLead_memid = qmr.memID"
                            . " WHERE 1=1"
                            . $checkTeamCode
                            . $checkTeamLead
                            . $checkTeamName
                            . $checkTeamType
                            . $checkTeamManager
                            . $checkTeamSkill
                            . " ORDER BY qtb.tCode DESC;";
                }
                $sqlGetAllData = mysql_query($sqlSelectTeamAll);
                if (mysql_num_rows($sqlGetAllData) >= 1) {
                    while ($row = mysql_fetch_assoc($sqlGetAllData)) {
                        echo '<tr class = "gradeX">';
                        echo '<td class = "center">' . $row['t_code'] . '</td>';
                        echo '<td>' . $row['t_Name'] . '</td>';
                        echo '<td>' . $row['t_lead_name'] . '</td>';
                        if ($row['t_type'] == "M") {
                            echo '<td class = "center">M (Main team)</td>';
                        }
                        if ($row['t_type'] == "S") {
                            echo '<td class = "center">S (Sub team)</td>';
                        }
                        if ($row['t_type'] == "T") {
                            echo '<td class = "center">T (Temporary)</td>';
                        }
                        $sqlGetAmount = "SELECT COUNT(*) AS amount FROM QRC_TEAM_MAPPING WHERE TEAM_ID LIKE '" . $row['t_code'] . "'";
                        $sqlGetAmountData = mysql_query($sqlGetAmount);
                        $AmountResult = mysql_fetch_assoc($sqlGetAmountData);
                        echo '<td class = "center">' . $AmountResult['amount'] . '</td>';
                        echo '<td>' . $row['t_remark'] . '</td>';
                        echo '<td class = "center">';
                        echo '<a href = "#modal-team" data-toggle = "modal" class = "btn btn-primary" onclick=editTeam("' . $row['t_code'] . '",' . $AmountResult['amount'] . ')><i class = "icon-document-line"></i> Edit</a>';
                        echo '<button class = "btn btn-danger" style="margin-left: 5px" onclick=deleteTeam("' . $row['t_code'] . '","' . $row['t_lead_id'] . '")><i class = "fa fa-trash-o"></i> Delete</button>';

                        echo '</td>';
                    }
                }
                ?>
            </tbody>
            <!-- // Table body END -->

        </table>
        <!-- // Table END -->

    </div>
</div>
<script src="assets/components/common/tables/responsive/assets/lib/js/footable.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/tables/responsive/assets/custom/js/tables-responsive-footable.init.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/modules/admin/notifications/gritter/assets/lib/js/jquery.gritter.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/modules/admin/modals/assets/js/bootbox.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/multiselect/assets/lib/js/jquery.multi-select.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/multiselect/assets/custom/js/multiselect.init.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/select2/assets/lib/js/select2.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/select2/assets/custom/js/select2.init.js?v=v1.0.2&sv=v0.0.1"></script>
<div class="modal fade" id="modal-team">

    <div class="modal-dialog">
        <div class="modal-content" style="width: 900px">

            <!-- Modal heading -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h2 class="modal-title">Team Builder Create/Edit</h2>
            </div>
            <!-- // Modal heading END -->

            <!-- Modal body -->
            <div class="modal-body">
                <div class="innerAll">
                    <div class="innerLR">
                        <table width="100%">
                            <tr>
                                <td align="right" style="width:250px">Team Code (หมายเลขทีมช่าง):</td>
                                <td align="left" style="width:250px">
                                    <?php
                                    $sqlSelectMaxValue = "SELECT count(*) as total FROM QRC_TEAM_BUILDER";
                                    $resultSet = mysql_query($sqlSelectMaxValue);
                                    $row = mysql_fetch_assoc($resultSet);
                                    if ($row['total'] == 0) {
                                        echo '<input type="text" class="form-control" id="team_code_form" disabled="true" value="B0001"/>';
                                    } else {
                                        $sqlSelectCodeValue = "SELECT max(tCode) as code FROM QRC_TEAM_BUILDER";
                                        $resultSets = mysql_query($sqlSelectCodeValue);
                                        $row = mysql_fetch_assoc($resultSets);
                                        $prefix = "B";
                                        $pieces = explode($prefix, $row[code]);
                                        if (count(intval($pieces[1])) == 1) {
                                            $strResult = $prefix . "000" . (intval($pieces[1] + 1));
                                        } else if (count(intval($pieces[1])) == 2) {
                                            $strResult = $prefix . "00" . (intval($pieces[1] + 1));
                                        } else if (count(intval($pieces[1])) == 3) {
                                            $strResult = $prefix . "0" . (intval($pieces[1] + 1));
                                        } else {
                                            $strResult = $prefix . (intval($pieces[1] + 1));
                                        }
                                        echo '<input type="text" class="form-control" id="team_code_form" disabled="true" value="' . $strResult . '"/>';
                                    }
                                    ?>
                                </td>
                                <td align="right" style="width:250px">Team Name (ชื่อทีม):</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="team_name_form"></td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Team Leader (หัวหน้าทีม):</td>
                                <td align="left" style="width:250px">
                                    <select class="form-control" id="team_lead_form" name="team_lead_form">
                                        <option value=""></option>
                                        <?php
                                        $sqlSelectMemType = "SELECT * FROM QRC_MEMBERS WHERE memRole in ('60004','60003');";
                                        $resultSets = mysql_query($sqlSelectMemType);
                                        while ($row = mysql_fetch_array($resultSets)) {
                                            echo '<option value="' . $row['memID'] . '">' . $row['memName'] . '</option>';
                                        }
                                        ?>
                                    </select>
                                </td>
                                <td align="right" style="width:250px">No. of Member (จำนวนลูกทีม):</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="no_of_member_form" disabled="true"></td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Type of Service (ประเภทของบริการ):</td>
                                <td align="left" style="width:250px" colspan="3">
                                    <select multiple="multiple" style="width: 100%;" id="select2_2_form" name="type_of_service">
                                        <optgroup label="Type of Service">
                                            <?php
                                            $sqlSelectProjectType = "SELECT * FROM QRC_TYPE_OF_SERVICE;";
                                            $resultSet = mysql_query($sqlSelectProjectType);
                                            while ($row = mysql_fetch_array($resultSet)) {
                                                echo '<option value="' . $row['service_id'] . '">' . $row['service_name'] . '</option>';
                                            }
                                            ?> 
                                        </optgroup>                              
                                    </select>
                                    <span id="waringteamMsg" style="color: red; font-size: 11px;"></span>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Team Type (ประเภททีม):</td>
                                <td align="left" style="width:250px">
                                    <select class="form-control" id="team_type_form" name="team_type_form">
                                        <option value=""></option>
                                        <option value="M">M (Main team)</option>
                                        <option value="S">S (Sub team)</option>
                                        <option value="T">T (Temporary)</option>
                                    </select>
                                </td>
                                <td align="right" style="width:250px">Team Manager (ผู้จัดการทีม):</td>
                                <td align="left" style="width:250px">
                                    <select class="form-control" id="team_t_manager_form" name="team_t_manager_form">
                                        <option value=""></option>
                                        <?php
                                        $sqlSelectMemType = "SELECT * FROM QRC_MEMBERS WHERE memRole ='60003';";
                                        $resultSets = mysql_query($sqlSelectMemType);
                                        while ($row = mysql_fetch_array($resultSets)) {
                                            echo '<option value="' . $row['memID'] . '">' . $row['memName'] . '</option>';
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Remark:</td>
                                <td align="left" colspan="3"><input type="text" class="form-control" id="team_remark_in_form"></td>

                            </tr>
                            <tr>
                                <td align="right" style="width:250px" colspan="2"><button class = "btn btn-primary" style="margin-left: 5px" id="team_create_edit_btn">Create/Edit (สร้าง/แก้ไข)</button></td>
                                <td align="left" style="width:250px" colspan="2"><button class = "btn btn-primary" style="margin-left: 5px" id="team_btn_cancel">Cancel (ยกเลิก)</button></td>

                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <!-- // Modal body END -->

        </div>
    </div>
    <input type="hidden" id="hideTeamSkill"/>
</div>
<script type="text/javascript">
    var createOrEditStateTeam = "Save";
    $(document).ready(function() {
        $("#dataTables-team").dataTable();
        $("#team_lead_form").change(function() {
            if ($("#team_lead_form").val() != "") {
                $("#no_of_member_form").val("1");
            } else {
                $("#no_of_member_form").val("");
            }
        });
        $("#new_team_btn").click(function() {
            createOrEditStateTeam = "Save";
            $("#waringteamMsg").empty();
        });
        $("#team_btn_cancel").click(function() {
            blockPage();
            createOrEditStateTeam = "Save";
            $("#modal-team").modal('hide');
            setTimeout(function()
            {
                $("#load_team").load("TeamMainPage.php?searchCondition=search_all", function() {
                    $.unblockUI();
                });

            }
            , 500);
        });
        $("#team_create_edit_btn").click(function() {
            blockPage();
            var teamCode = $("#team_code_form").val();
            var teamName = $("#team_name_form").val();
            var teamLeadId = $("#team_lead_form").val();
            var tSkill = $("#select2_2_form").val();
            var tType = $("#team_type_form").val();
            var tManagerID = $("#team_t_manager_form").val();
            var tRemark = $("#team_remark_in_form").val();
            if (createOrEditStateTeam == "Edit") {
                if (teamLeadId == "" || teamLeadId == null || tManagerID == "" || tManagerID == null) {
                    alert("กรุณาเลือก Team Leader หรือ Team Manager");
                } else {
                    if (tSkill == null || tSkill == "") {
                        tSkill = $("#hideTeamSkill").val();
                        var jqxhr = $.post("model/EditTeamBuilder.php?teamCode=" + teamCode + "&teamName=" + teamName + "&teamLeadId=" + teamLeadId + "&tSkill=" + tSkill + "&tType=" + tType + "&tManagerID=" + tManagerID + "&tRemark=" + tRemark);
                        jqxhr.success(function(data) {
                            if (data == 1) {
                                $("#modal-team").modal('hide');
                                setTimeout(function()
                                {
                                    $("#load_team").load("TeamMainPage.php?searchCondition=search_all", function() {
                                        $.unblockUI();
                                    });
                                    $.gritter.add({
                                        title: 'Success!',
                                        text: "<?= $config['msg_edit_success'] ?>"
                                    });
                                }
                                , 500);

                            } else {
                                alert(data);
                            }
                        });
                    } else {
                        var jqxhr = $.post("model/EditTeamBuilder.php?teamCode=" + teamCode + "&teamName=" + teamName + "&teamLeadId=" + teamLeadId + "&tSkill=" + tSkill + "&tType=" + tType + "&tManagerID=" + tManagerID + "&tRemark=" + tRemark);
                        jqxhr.success(function(data) {
                            if (data == 1) {
                                $("#modal-team").modal('hide');
                                setTimeout(function()
                                {
                                    $("#load_team").load("TeamMainPage.php?searchCondition=search_all", function() {
                                        $.unblockUI();
                                    });
                                    $.gritter.add({
                                        title: 'Success!',
                                        text: "<?= $config['msg_edit_success'] ?>"
                                    });
                                }
                                , 500);

                            } else {
                                alert(data);
                            }
                        });
                    }
                }
            } else {
                if (teamLeadId == "" || teamLeadId == null || tManagerID == "" || tManagerID == null) {
                    alert("กรุณาเลือก Team Leader หรือ Team Manager");
                } else {
                    var jqxhr = $.post("model/SavingTeamBuilding.php?teamCode=" + teamCode + "&teamName=" + teamName + "&teamLeadId=" + teamLeadId + "&tSkill=" + tSkill + "&tType=" + tType + "&tManagerID=" + tManagerID + "&tRemark=" + tRemark);
                    jqxhr.success(function(data) {
                        if (data == 1) {
                            $("#modal-team").modal('hide');
                            setTimeout(function()
                            {
                                $("#load_team").load("TeamMainPage.php?searchCondition=search_all", function() {
                                    $.unblockUI();
                                });
                                $.gritter.add({
                                    title: 'Success!',
                                    text: "<?= $config['msg_save_success'] ?>"
                                });
                            }
                            , 500);

                        } else {
                            alert(data);
                        }
                    });
                }
            }

        });
    });
    function editTeam(tID, amount) {
        blockPage();
        createOrEditStateTeam = "Edit";
        var jqxhr = $.post("model/GetAllTeamForEdit.php?teamID=" + tID);
        jqxhr.success(function(data) {
            $.unblockUI();
            $("#waringteamMsg").append("Leave empty for no change");
            obj = JSON.parse(data);
            $("#team_code_form").val(obj.t_code);
            $("#team_name_form").val(obj.t_Name);
            $("#team_lead_form").val(obj.t_lead_id);
            $("#hideTeamSkill").val(obj.tSkill);
            $("#no_of_member_form").val(amount);
            $("#team_type_form").val(obj.t_type);
            $("#team_t_manager_form").val(obj.t_manager_id);
            $("#team_remark_in_form").val(obj.t_remark);
        });
        jqxhr.error(function(data) {
            window.location.replace("error.php?error_msg=" + data);
        });
    }
    function deleteTeam(tID, memID) {
        if (confirm("Are you sure?"))
        {
            blockPage();
            var jqxhr = $.post("model/DeleteTeam.php?t_code=" + tID + "&memID=" + memID);
            jqxhr.success(function(data) {
                if (data == 1) {
                    setTimeout(function()
                    {
                        $("#load_team").load("TeamMainPage.php?searchCondition=search_all", function() {
                            $.unblockUI();
                        });

                        $.gritter.add({
                            title: 'Success!',
                            text: "<?= $config['msg_delete_success'] ?>"
                        });
                    }
                    , 500);
                } else {
                    alert("ไม่สามารถลบข้อมูลได้");
                }
            });
            jqxhr.error(function(data) {
                window.location.replace("error.php?error_msg=" + data);
            });
        }
        else
        {
            e.preventDefault();
        }
    }
    function blockPage() {
        $.blockUI({message: 'Operation in progress...', css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            }});
    }
</script>